﻿using Sheep_Breeding.Domain;
using Sheep_Breeding.ErrorCode;
using Sheep_Breeding.Infeartructure;
using Sheep_Breeding.Read.Api.Dtos;
using Sheep_Breeding.Read.Api.OperationServices.IServices;
using AutoMapper;

namespace Sheep_Breeding.Read.Api.OperationServices.Services
{
    public class PhaseBeginServices : IPhaseBeginServices
    {
        private readonly ILogger<PhaseBeginServices> logger;
        private readonly IBaseRepository<PhaseBegin> phaseBeginRepository;
        private readonly IBaseRepository<SheepFiles> sheepFilesRepository;
        private readonly IMapper mapper;

        public PhaseBeginServices(ILogger<PhaseBeginServices> logger, 
            IBaseRepository<PhaseBegin> phaseBeginRepository, 
            IBaseRepository<SheepFiles> sheepFilesRepository,
            IMapper mapper)
        {
            this.logger = logger;
            this.phaseBeginRepository = phaseBeginRepository;
            this.sheepFilesRepository = sheepFilesRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult<ApiPaging<List<PhaseBeginDto>>>> GetList(PhaseBeginQueryDto queryDto)
        {
            try
            {
                logger.LogInformation("开始获取期初列表");
                
                // 获取期初数据
                var phaseBegins = phaseBeginRepository.Getlist().Where(x => !x.IsDeleted).ToList();
                var sheepFiles = sheepFilesRepository.Getlist().Where(x => !x.IsDeleted).ToList();
                
                // 关联查询
                var query = from pb in phaseBegins
                           join sf in sheepFiles on pb.SheepFilesId equals sf.SheepFilesId
                           select new PhaseBeginDto
                           {
                               PhaseBeginId = pb.PhaseBeginId,
                               PhaseBeginNumber = pb.PhaseBeginNumber,
                               PhaseBeginDate = pb.PhaseBeginDate,
                               SheepFilesId = pb.SheepFilesId,
                               EarNumber = sf.EarNumber,
                               SheepType = sf.SheepType,
                               BuildingId = pb.BuildingId,
                               HouseName = "", // 栋舍名称需要从栋舍表获取，暂时留空
                               Field = pb.Field,
                               FielName = "", // 栏位名称需要从栏位表获取，暂时留空
                               SheepCount = pb.SheepCount,
                               Weight = pb.Weight,
                               Creator = pb.Creator,
                               CreateTime = pb.CreateTime,
                               Modifier = pb.Modifier,
                               ModifyTime = pb.ModifyTime,
                               Auditor = pb.Auditor,
                               AuditTime = pb.AuditTime,
                               IsDeleted = pb.IsDeleted
                           };

                // 应用筛选条件
                if (!string.IsNullOrEmpty(queryDto.EarNumber))
                {
                    query = query.Where(x => x.EarNumber.Contains(queryDto.EarNumber));
                }

                if (!string.IsNullOrEmpty(queryDto.SheepType))
                {
                    query = query.Where(x => x.SheepType == queryDto.SheepType);
                }

                // 获取总数
                var totalCount = query.Count();
                
                // 计算总页数
                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / queryDto.PageSize);
                
                // 应用分页
                var pageData = query.OrderByDescending(x => x.CreateTime)
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .ToList();
                
                // 创建分页结果
                var result = new ApiPaging<List<PhaseBeginDto>>
                {
                    TotalCount = totalCount,
                    TotalPage = totalPage,
                    PageIndex = queryDto.PageIndex,
                    PageSize = queryDto.PageSize,
                    PageData = pageData
                };

                // 设置成功状态
                result.success("获取期初列表成功", pageData);
                
                logger.LogInformation($"成功获取期初列表，共 {totalCount} 条记录，当前页 {queryDto.PageIndex}，每页 {queryDto.PageSize} 条");

                var apiResult = new ApiResult<ApiPaging<List<PhaseBeginDto>>>();
                apiResult.msg = "获取期初列表成功";
                apiResult.code = ApiREunm.Ok;
                apiResult.data = result;
                return apiResult;
            }
            catch (Exception ex)
            {
                logger.LogError($"获取期初列表异常: {ex.Message}");
                var apiResult = new ApiResult<ApiPaging<List<PhaseBeginDto>>>();
                apiResult.msg = "获取期初列表失败";
                apiResult.code = ApiREunm.Fail;
                return apiResult;
            }
        }
    }
}
